<template>
  <a-modal
    dialogClass="set-model-dialog"
    :visible="visible"
    title="修改技战法"
    @ok="handleOk"
    :destroyOnClose="true"
    width="910px"
    @cancel="onCancel"
  >
    <div class="model-content">
      <div class="rule-list">
        <a-list item-layout="horizontal" :data-source="ruleList">
          <template #renderItem="{ item, index }">
            <a-list-item>
              <template #actions>
                <span v-if="currentRuleIdId !== item.ruleId">
                  <a @click="removeRule(item, index)">删除</a>
                  <a @click="editRule(item, index)">编辑</a>
                </span>
                <span v-else>
                  <a @click="cancelHandle(item, index)">取消</a>
                  <a @click="saveRule(item, index)">保存</a>
                </span>
              </template>
              <div>
                <set-rule-item
                  :rule="item"
                  v-if="currentRuleIdId === item.ruleId"
                  @change="setRuleChangeHandle"
                ></set-rule-item>
                <rule-item :ruleData="item" v-else></rule-item>
              </div>
            </a-list-item>
          </template>
        </a-list>
        <a-button
          style="width: 100%; margin-top: 16px; margin-bottom: 8px"
          type="dashed"
          @click="addRule"
        >
          <plus-outlined />
          添加规则
        </a-button>
      </div>
    </div>

    <template #footer>
      <div class="rule-err-msg" v-for="item in errMsg">
        该规则已在
        <span>{{ item.xqdwName }}</span>
        <span>{{ item.name }}</span>
        模型中存在，请重新添加
      </div>
      <div class="rule-err-msg" v-if="ruleErrMsg">{{ ruleErrMsg }}</div>
      <a-button key="back" @click="onCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, reactive, watch, createVNode, toRaw } from 'vue';
import { ruleItemState } from '@/views/magic-cube/method-mode/set-ai-early-warning/js/typing';
import { queryRuleByModel, addModelRule } from '@/api/magic-cube/model-list';
import { deleteSjRule, updateSjRule } from '@/api/magic-cube/event-warning';
import { Modal } from 'ant-design-vue';
import RuleItem from '@/views/magic-cube/method-mode/components/rule-item/index.vue';
import SetRuleItem from '@/views/magic-cube/method-mode/components/set-rule-item/index.vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

// const errInfo = '温馨提示：红色预警 > 橙色预警 > 黄色预警 > 蓝色预警';
// const validator = (a: number, b: number, c: number, d: number) => {
//   return a > b && b > c && c > d;
// };
export default defineComponent({
  props: {
    modelId: {
      type: String,
      defaule: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['commit', 'update:visible'],
  components: { RuleItem, SetRuleItem },
  setup(props, { emit }) {
    const ruleData = reactive<ruleItemState>({
      ruleId: '', // 规则id
      period: 'D', // 周期（日-D，周-W，月-M）
      type: 'T', // 规则增长类型（T-同比，H-环比，N-数值）
      level1: 80, // 红色预警
      level2: 60, // 橙色预警
      level3: 40, // 黄色预警
      level4: 20, // 蓝色预警
    });
    const currentRuleIdId = ref('');
    const ruleErrMsg = ref('');
    const ruleList = ref<Array<ruleItemState>>([]);

    const periodOptions = ref([
      {
        label: '每日',
        value: 'D',
      },
      {
        label: '每周',
        value: 'W',
      },
      {
        label: '每月',
        value: 'M',
      },
    ]);

    const typeOptions = ref([
      {
        label: '同比',
        value: 'T',
      },
      {
        label: '环比',
        value: 'H',
      },
      {
        label: '数值',
        value: 'N',
      },
    ]);

    const handleOk = () => {
      // 校验
      //   const validate = validator(
      //     ruleData.level1,
      //     ruleData.level2,
      //     ruleData.level3,
      //     ruleData.level4,
      //   );
      //   if (validate) {
      //     ruleErrMsg.value = '';
      //   } else {
      //     ruleErrMsg.value = errInfo;
      //     return false;
      //   }
      emit('update:visible', false);
      emit('commit');
    };
    const onCancel = () => {
      ruleErrMsg.value = '';
      emit('update:visible', false);
    };

    const getRuleByModel = async () => {
      queryRuleByModel({ modelId: props.modelId })
        .then(res => {
          ruleList.value = res.data;
        })
        .catch(err => {
          console.log(err);
        });
    };
    const cancelHandle = (item, index) => {
      if (item.ruleId) {
        currentRuleIdId.value = '';
      } else {
        ruleList.value.splice(index, 1);
      }
    };
    const editRule = item => {
      Object.keys(item).forEach(key => {
        ruleData[key] = item[key];
      });
      currentRuleIdId.value = item.ruleId;
    };

    const saveRule = item => {
      if (item.ruleId) {
        updateRuleHttp();
      } else {
        addRuleHttp();
      }
    };

    const addRuleHttp = () => {
      addModelRule({ modelId: props.modelId, ...toRaw(ruleData) })
        .then(async res => {
          if (res) {
            await getRuleByModel();
            currentRuleIdId.value = '';
          }
        })
        .catch(err => {
          console.log('addRuleHttp err=', err);
        });
    };

    const setRuleChangeHandle = item => {
      Object.keys(item).forEach(key => {
        ruleData[key] = item[key];
      });
    };

    const updateRuleHttp = () => {
      updateSjRule(toRaw(ruleData))
        .then(async res => {
          if (res) {
            await getRuleByModel();
            currentRuleIdId.value = '';
          }
        })
        .catch(err => {
          console.log('update rule err=', err);
        });
    };

    const removeRule = (item, index) => {
      console.log('removeRule=', item, index);
      Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '是否删除该规则？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          deleteSjRule({ modelId: item.modelId, ruleId: item.ruleId })
            .then(res => {
              if (res) {
                getRuleByModel();
              }
            })
            .catch(err => {
              console.log('removeRule=', err);
            });
        },
      });
    };

    // 添加规则
    const addRule = () => {
      ruleList.value.push({
        ruleId: '', // 规则id
        period: 'D', // 周期（日-D，周-W，月-M）
        type: 'T', // 规则增长类型（T-同比，H-环比，N-数值）
        level1: 80, // 红色预警
        level2: 60, // 橙色预警
        level3: 40, // 黄色预警
        level4: 20, // 蓝色预警
      });
    };

    onMounted(() => {});

    watch(
      () => props.visible,
      () => {
        getRuleByModel();
      },
    );

    return {
      handleOk,
      onCancel,
      periodOptions,
      typeOptions,
      ruleData,
      ruleErrMsg,
      ruleList,
      currentRuleIdId,
      editRule,
      cancelHandle,
      removeRule,
      saveRule,
      addRule,
      setRuleChangeHandle,
    };
  },
});
</script>

<style lang="less" scoped>
.set-model-dialog {
}

.rule-err-msg {
  float: left;
  height: 32px;
  padding: 0 15px;
  padding-right: 160px;
  color: #eb9797;
  font-weight: 400;
  font-size: 14px;
  line-height: 32px;
}

.model-content {
  max-height: 300px;
  overflow: auto;
  :deep(.ant-list-item-action) {
    margin-left: 20px;
    a {
      margin-left: 5px;
    }
  }
}
</style>
